package com.mysoft.gfyx.common.concurrency.impl;

import com.mysoft.gfyx.common.concurrency.CacheAgentService;
import com.mysoft.gfyx.common.concurrency.CacheLockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.util.Random;
import java.util.UUID;

@Service
public class CacheAgentServiceImpl implements CacheAgentService {

    @Autowired
    private CacheLockService cacheLockService;

    private String hostName;

    CacheAgentServiceImpl() {
        try {
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (java.net.UnknownHostException e) {
            System.out.println("ERROR：获取主机名失败，原因是" + e.getMessage());
        }
    }

    public <T> T getCachedData(String key) {
        T res = cacheLockService.get(key);

        if (res == null) {
            String requestId = hostName + "_" + String.valueOf(Thread.currentThread().getId());
            System.out.println("线程ID：" + requestId + "竞争缓存锁...");
            boolean getLock = cacheLockService.getCacheLock(key, requestId);

            if (getLock) {
                System.out.println("线程ID：" + requestId + "获得缓存锁");
                return null;
            } else {
                int maxRetryTimes = 5;
                int currentRetryTimes = 0;
                while (currentRetryTimes < maxRetryTimes) {
                    try {
                        currentRetryTimes++;
                        Thread.sleep(500);
                        System.out.println("第" + currentRetryTimes + "次重试取缓存");
                        res = cacheLockService.get(key);
                        if (res != null) {
                            return res;
                        }
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                        maxRetryTimes = 0;
                    }
                }
            }
        }

        return res;
    }

    public <T> void setCacheData(String key, T data) {
        Random r = new Random();
        int randomExpiration = (int) Math.round(3600 * r.nextDouble());
        cacheLockService.set(key, data, 7200 + randomExpiration);

        String requestId = hostName + "_" + String.valueOf(Thread.currentThread().getId());
        System.out.println("线程ID：" + requestId + "释放缓存锁");
        cacheLockService.releaseCacheLock(key, requestId);
    }

    public <T> void setCacheDataAndSetExpiredTime(String key, T data, int expiredSecond) {
        cacheLockService.set(key, data, expiredSecond);

        String requestId = hostName + "_" + Thread.currentThread().getId();
        System.out.println("线程ID：" + requestId + "释放缓存锁");
        cacheLockService.releaseCacheLock(key, requestId);
    }

    public void deleteCacheDate(String key) {
        cacheLockService.delete(key);
    }
}
